/* eslint-disable */
/**
 * Created by GYL on 2018/8/24
 */
//项目进度管理-甘特图主页面
import React, { Component } from 'react';
import styles from '../EventPosting.less';
import { Icon, Select, Input, message, Tabs, Spin, Button, Popover } from 'antd';
import Container from "../../../components/common/Container";
import PublicService from "../../../services/PublicService";
import request from '../../../utils/request';
import Filtrate from '../../../components/common/Filtrate';
import JSGanttComponent from 'react-jsgantt';
import Edit_Small from './Edit_Small';
import Alter_GtteWrap from './Alter_GtteWrap';
import Record_GtteWrap from './Record_GtteWrap';
import Freeze_GtteWrap from './Freeze_GtteWrap';
import Alter_Edit from './Alter_Edit';
import File from './File';
import WBS_warp from './WBS_warp';
const TabPane = Tabs.TabPane;
const { Option } = Select;
const ButtonGroup = Button.Group;
const IconFont = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1315525_s1movn12eig.js',
});
class GtteWrap extends Component {

  componentDidMount() {


  }


  constructor(props) {
    super(props);

    const vAdditionalHeaders = {

      planStartTime: { title: '计划开始时间' },
      planEndTime: { title: '计划结束时间' },
      workTime: { title: '计划工期' },
      actualStartTime: { title: '实际开始时间' },
      actualEndTime: { title: '实际结束时间' },
      practicalWorkTime: { title: '实际工期' },
      status: { title: '事件状态' },
      proposeTask: { title: '前置任务' },
      confirmUserName: { title: '确认用户' },

      number: { title: '序号' },
    };

    this.state = {
      frozenReasons: '',
      djly: '',//冻结理由
      visible: '',//冻结弹框
      WBSdata: [],//wbs表格数据
      EditDataSmall: {},
      MyModal1VisibleSmall: false,
      MyModal1Visible: false,
      title: '项目xx编辑',
      addWrap: true,
      data: [],//甘特图
      editWrap: false,
      EditData: {},//大事件数组
      getAllProjectArr: [],//项目选取下拉
      projectId: '',//项目id
      Alter_GtteWrap: false,//变更开关
      changeId: '',//变更id
      Freeze_GtteWrap: false,
      subeventsId: '',
      eventId: '',
      spinning: false,
      WBSdata: [],
      FiletreeData: [],
      modalBtnLoading: false,
      warpBox: true ,                   //主体页面开关
      DownBoxThree:[]
    }






    this.editorOptions = {
      vCaptionType: 'Complete',  // Set to Show Caption : None,Caption,Resource,Duration,Complete,控制右边图形结尾显示
      vQuarterColWidth: 36,
      vDateTaskDisplayFormat: ' yyyy-mm-dd', // Shown in tool tip box
      vDayMajorDateDisplayFormat: ' yyyy-mm-dd', // Set format to display dates in the "Major" header of the "Day" view
      // vWeekMinorDateDisplayFormat: 'dd 日', // Set format to display dates in the "Minor" header of the "Week" view
      vLang: 0,
      vUseSingleCell: 0,
      vShowRes: 0,
      vShowCost: 0,
      vShowComp: 0,
      vShowDur: 0,
      vShowStartDate: 0,
      vShowEndDate: 0,
      vShowPlanStartDate: 0,
      vShowPlanEndDate: 0,
      vShowTaskInfoEndDate: 0,
      vShowTaskInfoLink: parseInt(this.vShowTaskInfoLink, 10), // Show link in tool tip (0/1)
      // Show/Hide the date for the last day of the week in header for daily view (1/0)
      // vTaskInfo: 0,
      vAdditionalHeaders: vAdditionalHeaders,//左边表格头部
      vEvents: {
        taskname: this.onEvent.bind(this, this.state.data),//点击触发
        res: 0,
        dur: 0,
        comp: 0,
        start: 0,
        end: 0,
        planstart: 0,
        planend: 0,
        cost: 0
      },
      vEventsChange: {
        taskname: this.editValue.bind(this, this.state.data),//编辑触发
        res: this.editValue.bind(this, this.state.data),
        dur: this.editValue.bind(this, this.state.data),
        comp: this.editValue.bind(this, this.state.data),
        start: this.editValue.bind(this, this.state.data),
        end: this.editValue.bind(this, this.state.data),
        planstart: this.editValue.bind(this, this.state.data),
        planend: this.editValue.bind(this, this.state.data),
        cost: this.editValue.bind(this, this.state.data)
      },
      vResources: [

      ],
      // vEventClickRow: console.log,
      vTooltipDelay: 0,
      vDebug: false,
      vEditable: false,//是否可以编辑
      vUseSort: false,
      vFormatArr: ['Day', 'Week', 'Month'],//切换控制日期选择,日,周,月
    };
  }

  componentDidMount() {


    this.getProjectFileTree(this.props.id)
    this.getWbsData(this.props.id)

    const params = this.f1.getForm().getFieldsValue();
    params.projectId = this.props.id
    this.setState({
      params,
      projectId: this.props.id
    })
    //获取甘特图数据
    request({
      url: '/pm-web/projectmanage/progress/getGanttData',
      method: 'POST',
      data: params
    }).then(data => {
      // console.log(data)
      if (data.rc === 0) {

        this.setState({
          data: data.ret,
          spinning: false
        })
      }
    })

    request({
      url: '/pm-web/projectmanage/progress/getAllProject',
      method: 'POST',
      data: { userId: PublicService.getCookie('userId'), projectId: this.props.id }
    }).then(data => {

      if (data.rc === 0) {
        let arr = []
        data.ret.retList.forEach(item => {
          arr.push({ value: item.projectId, name: item.projectName })
        });

        this.setState({
          getAllProjectArr: arr
        })

      }
    })

    this.dropDownBoxThree()
  }

  dropDownBoxThree = () => {
    request({
      url: '/pm-web/projectmanage/findData/dropDownBoxThree',
      method: 'GET',
      params: { projectId: this.props.id }
    }).then(data => {
      if(data.rc === 0) {
        this.setState({
          DownBoxThree:data.ret
        })
      }
    })
  }



  editValue(list, task, event, cell, column) {
    // tslint:disable-next-line:triple-equals
    const found = list.find(item => item.pID == task.getOriginalID());
    if (!found) {
      return;
    } else {
      found[column] = event ? event.target.value : '';
    }
    // console.log(found);
  }

  change() {
    // console.log('change:', this.editor);
    // console.log('change2:', this.editorTwo);
  }

  setLanguage(lang) {
    this.editorOptions.vLang = lang;
    this.editor.setOptions(this.editorOptions);
  }

  getWbsData = (id) => {
    request({
      url: '/pm-web/projectmanage/progress/getWbsData',
      method: 'POST',
      data: { projectId: id }
    }).then(data => {
      if (data.rc === 0) {
        this.setState({
          WBSdata: data.ret.list
        })
      }
    })
  }

  customLanguage() {
    // this.editorOptions.languages = {
    //   'pt-BR': {
    //     'auto': 'Automático testing'
    //   },
    //   'en': {
    //     'auto': 'Auto testing'
    //   }
    // };
    this.editor.setOptions(this.editorOptions);
  }

  changeObject() {
    this.state.data.randomNumber = Math.random() * 100;
  }

  changeData() {
    this.state.data = Object.assign({}, this.state.data,
      { randomNumber: Math.random() * 100 });
  }



  // 取消保存
  ModalCancel = (type) => {
    let t = this;
    t.setState({
      [type]: false,
      modalBtnLoading: false
    })
  };






  //保存按钮事件
  onModalSave = (v) => {
    // console.log(v)


  }


  selectedChange(fun, nextParams, paramName, index, value) {
    // console.log(fun, nextParams, paramName, index, value)


    let t = this;
    let params = {};
    params[paramName] = value;
    if (paramName) {
      t.setState({ params }, () => {
      });
    }
    if (typeof fun === "function") {
      fun(value);
      if (nextParams)
        t.props.form.setFieldsValue({
          [nextParams]: ''
        })
    }
  }



  onEvent = (list, task, event, cell, column) => {
    // console.log(list, task.getLink(), event, cell, column)
    // task.getOriginalID()  获取点击项目的id
    //判断是否能点击打开详情,id中含有#的id无法打开
    if (task.getOriginalID().indexOf("#") != -1) {

      return
    }

    if (task.getParent() == 0) {
      return
    }

    if (Number(task.getParItem().getOriginalID() < 5)) {
      //大事件
      request({
        url: '/pm-web/projectmanage/eventinfo/getEventInfoByEventId',
        method: 'POST',
        data: { eventId: task.getOriginalID() }
      }).then(data => {
        // console.log(data)
        if (data.rc === 0) {
          this.setState({
            EditData: data.ret,
            MyModal1Visible: true,
            title: task.getName(),
            eventId: task.getOriginalID()
          })


        }
      })
    } else {

      //小事件
      this.setState({
        // EditDataSmall:data.ret,
        subeventsId: task.getOriginalID(),
        MyModal1VisibleSmall: true,
        title: task.getName()
      })
    }




  }

  onModalSaveSmall = (v) => {
    this.setState({
      MyModal1VisibleSmall: false,
    })
    this.onSubmit(1, 10, this.state.projectId)
  }

  //查询
  onSubmit = (page, size, id) => {
    const params = this.f1.getForm().getFieldsValue();
    params.projectId = id
    this.setState({
      params,
      spinning: true
    })

    request({
      url: '/pm-web/projectmanage/progress/getGanttData',
      method: 'POST',
      data: params
    }).then(data => {
      // console.log(data)
      if (data.rc === 0) {

        this.setState({
          data: data.ret,
          spinning: false,

        })
      }
    })

    request({
      url: '/pm-web/projectmanage/progress/getAllProject',
      method: 'POST',
      data: { userId: PublicService.getCookie('userId'), projectId: this.props.id }
    }).then(data => {

      if (data.rc === 0) {
        let arr = []
        data.ret.retList.forEach(item => {
          arr.push({ value: item.projectId, name: item.projectName })
        });

        this.setState({
          getAllProjectArr: arr,

        })

      }
    })



  }


  onBack = () => {
    this.props.onBack()
  }

  onBackRecord = () => {
    this.setState({
      Record_GtteWrap: false,
      warpBox: true
    })
  }

  onBackFreeze = () => {
    this.setState({
      Freeze_GtteWrap: false,
      warpBox: true
    })
  }

  onBackAlterG = () => {
    this.setState({
      Alter_GtteWrap: false,
      warpBox: true
    })
  }

  handleChange = (value) => {
    // console.log(`selected ${value}`);
    this.onSubmit(1, 10, value)
    this.setState({
      projectId: value
    })

    this.getWbsData(value)
    this.getProjectFileTree(value)
  }

  //项目变更按钮
  onAlter = () => {
    this.setState({
      spinning: true
    })
    // console.log('项目变更')
    let params = {
      projectId: this.state.projectId,
      userId: PublicService.getCookie('userId')
    }
    request({
      url: '/pm-web/projectmanage/progress/projectChangeVerification',
      method: 'POST',
      data: params
    }).then(data => {
      if (data.rc === 0) {
        // console.log(data)
        this.setState({
          changeId: data.ret.changeId,
        }, () => {
          this.setState({
            Alter_GtteWrap: true,
            warpBox: false
          })
        })

      } else {
        message.warning(`${data.err}`)
      }
      this.setState({
        spinning: false
      })
    })

  }

  onRecord = () => {
    request({
      url: '/pm-web/projectmanage/eventinfo/judgeConfigurationAuthority',//查询是否具有权限
      method: 'POST',
      data: { userId: PublicService.getCookie('userId'), buttonName: '变更记录', projectId: this.state.projectId }
    }).then(data => {
      if (data.rc === 0) {
        if (data.ret.type) {
          this.setState({
            Record_GtteWrap: true,
            warpBox: false
          })
        } else {
          message.warning("用户权限不足!")
        }
      }
    })

  }

  //修改事件
  onFreeze = () => {
    // console.log('项目冻结')
    let params = {
      projectId: this.state.projectId,
      userId: PublicService.getCookie('userId')
    }
    request({
      url: '/pm-web/projectmanage/progress/projectFreezeRecovery',
      method: 'POST',
      data: params
    }).then(data => {
      if (data.rc === 0) {
        // console.log(data)
        this.setState({
          changeId: data.ret.changeId,
          frozenReasons: data.ret.frozenReasons
        }, () => {
          this.setState({
            Freeze_GtteWrap: true,
            warpBox: false
          })
        })
      } else {
        message.warning(`${data.err}`)
      }
    })
  }
  //直接解冻
  onZjFreeze = () => {
    this.setState({
      spinning: true
    })
    let params = {
      projectId: this.state.projectId,
      userId: PublicService.getCookie('userId')
    }
    request({
      url: '/pm-web/projectmanage/progress/projectFreezeRecovery',
      method: 'POST',
      data: params
    }).then(data => {
      if (data.rc === 0) {
        let paramsTwo = {
          projectId: this.state.projectId,
          changeId: data.ret.changeId,
        }
        request({
          url: '/pm-web/projectmanage/progress/projectFreezeUpdateTwo',
          method: 'POST',
          data: paramsTwo
        }).then(data => {
          if (data.rc === 0) {
            message.success('解冻成功!')

          }
          this.setState({
            spinning: false
          })

        })

      } else {
        this.setState({
          spinning: false
        })
        message.warning(`${data.err}`)
      }
    })


  }

  //项目冻结
  onProgressFreeze = () => {
    this.setState({
      spinning: true
    })
    let params = {
      projectId: this.state.projectId,
      userId: PublicService.getCookie('userId'),
      frozenReasons: this.state.djly
    }
    request({
      url: '/pm-web/projectmanage/progress/projectFreezing',
      method: 'POST',
      data: params
    }).then(data => {
      if (data.rc === 0) {
        message.success('项目冻结成功')
        this.setState({
          visible: false
        })
      } else {
        message.warning(`${data.err}`)
      }

      this.setState({
        spinning: false
      })
    })
  }

  onBackAll = () => {
    this.props.onBack()
  }


  handleVisibleChange = visible => {
    // console.log(visible)
    let params = {
      projectId: this.state.projectId,
      userId: PublicService.getCookie('userId')
    }
    request({
      url: '/pm-web/projectmanage/progress/projectFreezingJudgment',
      method: 'POST',
      data: params
    }).then(data => {
      if (data.rc == 0) {
        this.setState({ visible });
      } else {
        message.warning(data.err)
      }
    })


  };

  onChangeInput = (v, val) => {
    this.setState({
      [v]: val.target.value
    })
  }

  //导出
  exportBtn = (val) => {
    let t = this;
    window.location.href = '/pm-web/projectmanage/eventinfo/exportManagement?' + PublicService.paramSerializer({
      ...t.state.params,
    })
  };

  //获取文件树
  getProjectFileTree = (id) => {
    request({
      url: '/pm-web/projectmanage/progress/getProjectFileTree',
      method: 'POST',
      data: { projectId: id }
    }).then(data => {
      if (data.rc === 0) {
        this.setState({
          FiletreeData: data.ret.treeList
        })
      }
    })

  }

  ResetForm = () => {

    setTimeout(() => {
      this.onSubmit(1, 10, this.state.projectId)
    }, 500)
  }

  //变更甘特图
  getAlter_GtteWrap = () => {
    return (
      <Alter_GtteWrap changeId={this.state.changeId} id={this.state.projectId} onBackAll={this.onBackAll} />
    )
  }
  //项目解冻
  getFreeze_GtteWrap = () => {
    return (
      <Freeze_GtteWrap changeId={this.state.changeId} id={this.state.projectId} onBackAll={this.onBackAll} frozenReasons={this.state.frozenReasons} />
    )
  }
  //变更记录
  getRecord_GtteWrap = () => {
    return (
      <Record_GtteWrap changeId={this.state.changeId} id={this.state.projectId} />
    )
  }

  //主体页面按钮
  getWarpBtn = () => {
    const { spinning } = this.state;
    return (
      <>
        <ButtonGroup loading={spinning} size="small" style={{ position: 'absolute', top: '1vh', right: 100, fontSize: 16 }}>
          <Button onClick={this.exportBtn} loading={spinning}>项目导出</Button>
          <Button onClick={this.onAlter} loading={spinning}>项目变更</Button>
          <Button onClick={this.onRecord} loading={spinning}>变更记录</Button>
          <Popover
            content={
              <div style={{ width: 200, height: 80, display: 'flex', alignItems: 'center', justifyContent: 'space-around' }}>
                <Button loading={spinning} type="primary" onClick={this.onZjFreeze}>直接解冻</Button>
                <Button loading={spinning} onClick={this.onFreeze}>修改事件</Button>
              </div>
            }
            title="解冻"
          >
            <Button loading={spinning}> 项目解冻</Button>
          </Popover>
          <Popover
            content={
              <div style={{ width: 500, height: 80, display: 'flex', alignItems: 'center' }}>
                <Input placeholder="请输入" onChange={this.onChangeInput.bind(this, 'djly')} value={this.state.djly} />
                <Button loading={spinning} type="primary" onClick={this.onProgressFreeze}>确认冻结</Button>
              </div>
            }
            title="冻结理由"
            trigger="click"
            visible={this.state.visible}
            onVisibleChange={this.handleVisibleChange}
          >
            <Button loading={spinning}> 项目冻结</Button>
          </Popover>

        </ButtonGroup>
      </>
    )
  }




  render() {
    let t = this
    let width = document.body.clientWidth;
    const height = document.body.clientHeight;
    let containerHeight = '80vh';
    let tableHeight = 310;
    if (width > 1367) {
      tableHeight = 380;
      containerHeight = '84vh';
    }
    const {DownBoxThree} = this.state;
    const items = [
      {
        type: 'autoComplete',
        label: '事件名称',
        placeholder: '请输入 ..',
        paramName: 'eventName',
        options:DownBoxThree,
        width:240
      },
      {
        type: 'select',
        label: '事件阶段',
        paramName: 'eventStage',
        options: [
          { text: '全部', value: '' },
          { text: '项目前期', value: '1' },
          { text: '项目实施', value: '2' },
          { text: '项目验收', value: '3' },
          { text: '项目结算', value: '4' },
        ],
      },
      {
        type: 'select',
        label: '事件状态',
        paramName: 'eventType',
        options: [
          { text: '全部', value: '' },
          { text: '未开始', value: '1' },
          { text: '进行中', value: '2' },
          { text: '逾期开始', value: '3' },
          { text: '逾期结束', value: '4' },
          { text: '已完成', value: '5' },
          { text: '逾期完成', value: '6' },
          { text: '审核中', value: '7' },

        ],
      },
      {
        type: 'select',
        label: '甘特图模式',
        paramName: 'type',
        options: [
          { text: '计划', value: 1 },
          { text: '全部', value: 2 },
        ],
      },
    ];

    const { spinning, modalBtnLoading } = this.state;
    return (
      <div className={styles.box}>
        <Tabs defaultActiveKey="1" size="small" style={{ position: 'relative' }}>
          <TabPane tab="甘特图视图" key="1">
            <div>
              {this.state.Alter_GtteWrap && this.getAlter_GtteWrap()}
              {this.state.Freeze_GtteWrap && this.getFreeze_GtteWrap()}
              {this.state.Record_GtteWrap && this.getRecord_GtteWrap()}
              {this.state.warpBox &&
                //进度甘特图
                <div className={styles.warpBox}>
                  <Spin spinning={spinning} size='large'>
                    <div className={styles.Top_Box}>
                      <Filtrate
                        items={items}
                        ref={ref => { this.f1 = ref }}
                        submit={this.onSubmit.bind(this, 1, 10, this.state.projectId)}
                        ResetForm={this.ResetForm}
                      />
                    </div>
                    <div style={{ flex: 1, backgroundColor: '#f6f6f18a', overflow: 'auto' }} className={styles.gantt}>
                      {/* 大事件编辑页面 */}
                      {
                        this.state.MyModal1Visible && <Alter_Edit
                          onCancel={this.ModalCancel.bind(this, 'MyModal1Visible')}
                          EditData={this.state.EditData}
                          onModalSave={this.onModalSave}
                          maskClosable={true}
                        />
                      }
                      {/* 子事件编辑页面 */}
                      {
                        this.state.MyModal1VisibleSmall && <Edit_Small
                          onCancel={this.ModalCancel.bind(this, 'MyModal1VisibleSmall')}
                          EditData={this.state.EditDataSmall}
                          onModalSave={this.onModalSaveSmall}
                          title={this.state.title}
                          id={this.state.subeventsId}
                          visible={this.state.MyModal1VisibleSmall}

                        />
                      }
                      <div style={{ flex: 1, overflow: 'auto' }} className={styles.JSGanttComponentBox}>
                        <JSGanttComponent data={this.state.data} options={this.editorOptions} />
                      </div>
                    </div>
                  </Spin>
                </div>
              }

              {this.state.warpBox && this.getWarpBtn()}

              {
                this.state.warpBox && <div style={{ position: 'absolute', top: '1vh', right: 620 }}>
                  <span style={{ marginLeft: 15, marginRight: 15 }}></span><Select defaultValue={this.state.projectId ? this.state.projectId : this.props.id} style={{ width: 220 }} onChange={this.handleChange} size='small'>
                    {
                      this.state.getAllProjectArr.map((item) => {
                        return (
                          <Option value={item.value}>{item.name}</Option>
                        )
                      })
                    }
                  </Select>
                </div>
              }
              <IconFont type="icon-guanbi"
                onClick={
                  this.state.warpBox ? this.onBack :
                    this.state.Alter_GtteWrap ? this.onBackAlterG :
                      this.state.Record_GtteWrap ? this.onBackRecord : this.onBackFreeze
                }
                style={{ position: 'absolute', top: '1vh', right: 20, cursor: 'pointer', fontSize: 24 }} />

            </div>
          </TabPane>
          <TabPane tab="WBS视图" key="2" forceRender>
            <Container
              style={{ height: containerHeight, position: "relative", overflow: 'auto', padding: 10 }}
              header={true}
            >
              <WBS_warp WBSdata={this.state.WBSdata} />
            </Container>
          </TabPane>
          <TabPane tab="文件视图" key="3" forceRender>
            <File FiletreeData={this.state.FiletreeData} />
          </TabPane>



        </Tabs>
      </div>
    );


  }

}
export default GtteWrap;

